define(function(require, exports, module) {
    require("{component}dialog/zepto.dialog.css");
    var md5 = require('{component}md5/md5'),
        dialog = require('{component}dialog/zepto.dialog'),
        MiniIM = require('candy');

    share.disconnect = function() {
        share.pageLoad(false,$('body'));
        try {
            share.PMSG.removeAllHandler();
            MiniIM.disconnect();
            //MiniIM.onWindowUnload();
            share.PMSG = null;
        } catch(e){console.log(e)};
        share.delIdPage('messageList');
    };

    share.message = function() {

        this.opt = {
            addMessageToChat : function(){},
            addUserToList : function(){} 
        }; 

        this.userInfo = {};
        this.StatusChange = {};
        this.ContactsHandler = {};
        this.MessageHandler = {};
        this.MessageErrorHandler = {};
        this.PresenceHandler = {};
        this.ArchiveHandler = {};
        this.OnlineUserHandler = {};
        this.UnreadHandler = {};
        this.TimeHandler = {};

        this.init = function(opt) {
            var tthis = this;    
            this.userInfo = share.userInfo();
            this.MessageHandler.proccess = function(obj, args) {
                //console.log("Get New Message:"+JSON.stringify(args));
                if(seajs.moduleUI == 'messageConversation') {
                   tthis.addMessageToChatRoom(args);
                } else  {
                   tthis.addMessageToMessageList(args);
                }

            };

            this.MessageErrorHandler.proccess = function(obj, args) {
                //console.log("Message Error:" + JSON.stringify(args));
                //console.log("Message Error:" + args);
                tthis.showMessageError(args.code, args.message, args.uniqueId);
            };

            this.PresenceHandler.proccess = function(obj, args) {
                //console.log("PresenceHandler: " + JSON.stringify(args));
            };
            this.ArchiveHandler.proccess = function(obj, args) {
                //console.log("Archive: " + JSON.stringify(args));
                tthis.addHistroyMessageToChatRoom(args);
            };
            this.ContactsHandler.proccess = function(obj, args) {
                //console.log('ContactsHandler');
                share.pageLoad(false,$('body'));
                //console.log("Get Contacts:" + JSON.stringify(args));
                tthis.contactsToList(args.contacts);
            };
            this.UnreadHandler.proccess = function(obj, args) { 
                //console.log('unread',args);
                //console.log("Get Unread Message:"+JSON.stringify(args));
                if (args.messages) {                
                    for (var i in args.messages) {
                        var arr = args.messages[i];
                        for (var j in arr) {
                            tthis.addMessageToMessageList(arr[j]);
                        }
                    }
                }
            };
            this.OnlineUserHandler.proccess = function(obj, args) {
                //console.log("Get Online users:" + JSON.stringify(args));
            };
            this.TimeHandler.proccess = function(obj, args) {
                //console.log("Time Handler: " + JSON.stringify(args));
            };
            this.StatusChange.proccess = function(obj, args) {
                switch(args.status) {
                    case Strophe.Status.CONNECTED:
                        MiniIM.log("CONNECTED");
                        break;
                    case Strophe.Status.ATTACHED:
                        MiniIM.log("Register all need handlers after login successfully");
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.MESSAGE, tthis.MessageHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ERROR, tthis.MessageErrorHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.PRESENCE, tthis.PresenceHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ARCHIVE, tthis.ArchiveHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.RECENT_CONTACTS, tthis.ContactsHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.UNREAD, tthis.UnreadHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ONLINE_USERS, tthis.OnlineUserHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.TIME, tthis.TimeHandler);
                        break;
                    case Strophe.Status.DISCONNECTED:
                        if (seajs.moduleUI.indexOf('message') < 0) { 
                            MiniIM.log("DISCONNECTED");
                        } else {
                           if (comfirm('You\'re now offline on Messages. Reconnect?')) {
                               share.disconnect();
                               setTimeout(function() {
                                   window.location.href = '#messageList/whole';
                               },500)
                           }
                        }
                        break;
                    case Strophe.Status.ERROR:
                        MiniIM.log("ERROR");
                        break;
                    case Strophe.Status.CONNFAIL:
                        MiniIM.log("CONNFAIL");
                }
            };
            this.initConnect();
        }

        this.initConnect = function() {
            share.pageLoad(true,$('body'));
            var tthis = this;
            var obj = {
                url : seajs.data.vars.apiAccessUrl + 'bosh_client',
                type : 'POST',
                success : function(data) {
                    if (data.return_code == 0) {
                            MiniIM.init('/http-bind-new/?random=' + data.random, messageName, data.session_id);
                            MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.CONN_STATUS, tthis.StatusChange);
                            MiniIM.attach(data.jid, data.sid, data.rid);
                            tthis.getContacts();
                    } else {
                        share.pageLoad(false,$('body'));
                        alert(data.message);
                    }
                }, 
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                }
            };

            $.ajax(share.ajaxControl(obj));
        },

        this.sendMessage = function(obj) {
            var messageContent = obj.messageContent,
                sender = obj.sender,
                senderId = obj.senderId,
                receiver = obj.receiver,
                receiverId = obj.receiverId,
                message_obj = obj.message_obj; 

            if (messageContent) {
                MiniIM.Action.sendMessage(receiver, messageContent, null, {uniqueId: message_obj.uniqueId, senderId: senderId, receiverId: receiverId});
            }
        },

        this.getContacts = function() {
            
            MiniIM.Action.loadRecentContacts();
        },

        this.removeConversation = function(username) {
            MiniIM.Action.removeArchive(username);
        },

        this.addUserToChatRoom =  function(userName,userInfos) {
            //console.log('addUserToChatRoom',userName,userInfos);
        },
        
        this.addMessageToChatRoom = function(message) {
            if (message.type == 'chat') {
                this.opt.addMessageToChat(message,true); 
            }
        },

        this.markAllMessageRead = function(username) {
            MiniIM.Action.markAllMessagesRead(username);
        },

        this.contactsToList= function(contacts) {
             var users=[]; 
             for (var i in contacts) {    
                 users.push(i);
             }
             //console.log(contacts);
             this.ajaxUserInfo(users.join(','),contacts);  
        },

        this.addMessageToMessageList = function(message) {

             var dom = $('#messageList').find('li[username="'+message.sender+'"]'),
                 num = dom.find('.num').html();

             dom.find('.content').html(message.message);
             num = (num == '') ? 1 : (parseInt(num)+1);
             dom.find('.num').html(num).show();  
        },
 
        this.ajaxUserInfo = function(userInfos,contacts) {
           var tthis = this,dom=$('#messageList').find('.messagelist');
           var  obj = {
                url : seajs.data.vars.apiAccessUrl+'users_profile',
                type : 'POST',
                data : { users: userInfos},
                success : function(data) {
                    share.pageLoad(false,$('body'));
                    if (data.result == 1) {
                        var userArr=[],arr = data.data;
                        for (var i in arr) {
                             var user =  arr[i];
                                 user.name = i;
                                 user = tthis.mergingData(user,contacts);
                                 user.formatTime = share.formatChatDate(user.time);
                                 userArr.push(user);
                        }
                        share.setStorage('messageList', JSON.stringify(userArr));
                        userArr = tthis.sort(userArr);
                        tthis.opt.addUserToList(userArr); 
                        tthis.loadUnreadMessages(); 
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                },
                complete : function(xhr, status) {
                    share.ajaxEndB(dom);
                }
            };

            share.ajaxStartB(dom);
            $.ajax(share.ajaxControl(obj));
        },      

        this.mergingData = function(user,contacts) {
            for(var x in contacts) {
                if (user.name == x) {
                    for (var j in contacts[x]) {
                         user[j] = contacts[x][j];
                    }
                }
            }
            return user;
        },

        this.addHistroyMessageToChatRoom = function(messageObj) {
            var arr = messageObj.messages;   
            $('#messageConversation').find('.message_loading').hide();
            for (var i = arr.length-1; i > -1 ; i--) {
                 var message = messageObj.messages[i];
                 this.opt.addMessageToChat(message,false); 
            }
        },

        this.getArchive = function(receiver,receiver_id,type,timepoint) {
            if (type == 'personal_chat') {
                MiniIM.Action.loadArchive(receiver, receiver_id, MiniIM.TYPE.PRIVATE, timepoint || null,10);
            } 
        },
 
        this.constructNewMessage = function(message_content, sender, msg_time) {
            var myDate = new Date(); 
            var message_obj = {"message" : message_content, "time" : (msg_time || myDate.getTime()), "sender" : sender};
            if (!msg_time) {
                message_obj.uniqueId = md5(message_content + myDate.getTime());
            }
            return message_obj;
        },
       
        this.removeArchive = function(username) {
             MiniIM.Action.removeArchive(username);
        },
 
        this.loadUnreadMessages = function() {
             MiniIM.Action.loadUnreadMessages();
        },
          
        this.sort = function(array) {
             var temp,length = array.length;
             for(var i=0;i<length;i++) {
                    for(var j=0;j<length-1.;j++) {
                        if (new Date(array[j].time).getTime() < new Date(array[j + 1].time).getTime()) {
                            temp = array[j + 1];
                            array[j + 1] = array[j];
                            array[j] = temp;
                        }
                    } 
             }
             return array; 
        },

        this.showMessageError = function(code, reason, uniqueId) { 
             var err_note = 'Failed sending messages.';
             //console.log(code);
             if (code == 2003) {
                 dialog.open({
                    type : 'payDialog',
                    dom : $('#messageConversation').find('.body_all'),
                    cover : true,
                    close : true,
                    positionRelative:true
                 });
             } else {
                 share.error('alert','Oops! Something\'s not right. Try again later.'); 
             }
             var dom = $('#messageConversation').find('li[uniqueid="'+uniqueId+'"]');

             var html = "<div class='message_fail'></div>"; 
             dom.find('.bubble_orange_right').after(html);
        },

        this.removeAllHandler = function() {
             return MiniIM.Handler.removeAllHandler();
        }

    };
});
